package com.iexbuy.ihg.ui.fragment;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.iexbuy.ihg.App;
import com.iexbuy.ihg.R;
import com.iexbuy.ihg.common.CommUtil;
import com.iexbuy.ihg.common.ExtraKeyConstant;
import com.iexbuy.ihg.entity.DealHistoryDetailObject;
import com.iexbuy.ihg.entity.XiaoFeiOrderConfirmObject;
import com.iexbuy.ihg.net.ServiceHelper;
import com.iexbuy.ihg.ui.activity.MainTabActivity;
import com.iexbuy.ihg.utils.JsonUtils;
import com.iexbuy.ihg.utils.StringUtil;
import com.iexbuy.ihg.utils.ToastUtils;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

public class OrderDetailFrament extends BaseFragment {
	
	private static OrderDetailFrament homeFragmentInstent;

	@ViewInject(R.id.msgListLayout)
	private PullToRefreshLayout msgListRefreshLayout;
	@ViewInject(R.id.listView)
	private ListView listView;

	private LinearLayout listHeaderView;
	@ViewInject(R.id.productIcon)
	private ImageView productIcon;
	@ViewInject(R.id.productName)
	private TextView productName;
	@ViewInject(R.id.orderStatus)
	private TextView orderStatus;
	@ViewInject(R.id.oldPrice)
	private TextView oldPrice;
	@ViewInject(R.id.paidPrice)
	private TextView paidPrice;
	@ViewInject(R.id.expressInfoLayout)
	private LinearLayout expressInfoLayout;
	@ViewInject(R.id.productInfoLayout)
	private LinearLayout productInfoLayout;
	@ViewInject(R.id.orderDetailLayout)
	private LinearLayout orderDetailLayout;
	@ViewInject(R.id.consumeGoldCoinLayout)
	private LinearLayout consumeGoldCoinLayout;
	@ViewInject(R.id.payBtnLayout)
	private LinearLayout payBtnLayout;
	@ViewInject(R.id.cancelOrderBtn)
	private Button cancelOrderBtn;

	private static XiaoFeiOrderConfirmObject xiaoFeiOrderConfirmObject;
	private static DealHistoryDetailObject dealHistoryDetailObject;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		homeFragmentInstent = this;
	}

	@Override
	protected View _onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_order_detail, container, false);
		ViewUtils.inject(this, rootView);
		initView(rootView);
		return rootView;
	}

	private void initView(View rootView) {
		mBaseActivity.setTitle(getResources().getString(R.string.title_order_detail));
		mBaseActivity.setTitleLayoutVisibility(true);
		mBaseActivity.setHomeActivity(false);

		initOrderDetailData();
	}

	private void initOrderDetailData() {
		if (xiaoFeiOrderConfirmObject == null) return;
		HashMap<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("orderId", xiaoFeiOrderConfirmObject.getId());
		ServiceHelper.send(mBaseActivity, ServiceHelper.GET_DEAL_HISTORY_DETAIL, paramMap,
				new RequestCallBack<String>() {
					@Override
					public void onStart() {
					}

					@Override
					public void onCancelled() {
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						dealHistoryDetailObject = JsonUtils.parseJsonStrToObject(JsonUtils.getJsonSubStringByKey(responseInfo.result, "body"), DealHistoryDetailObject.class);
						initOrderlView();

					}

					@Override
					public void onFailure(HttpException error, String msg) {
					}
				});
	}

	private void initOrderlView() {
		if (dealHistoryDetailObject == null) return;
		//分页
		App.bitmapUtils.display(productIcon, dealHistoryDetailObject.getThumbnailUrl());
		productName.setText(dealHistoryDetailObject.getName());
		orderStatus.setText("订单状态：" + CommUtil.getStatusNameFromCode(dealHistoryDetailObject.getStatus()));

		if ("2".equalsIgnoreCase(dealHistoryDetailObject.getPayType())) {//现金
			oldPrice.setText("商品原价：" + new BigDecimal(StringUtil.checkNull(dealHistoryDetailObject.getGoodsOrgPriceMoney(), "0")).setScale(2, BigDecimal.ROUND_DOWN) + "元");
			paidPrice.setText("实际付款：" + new BigDecimal(StringUtil.checkNull(dealHistoryDetailObject.getPayMoney(), "0")).setScale(2, BigDecimal.ROUND_DOWN) + "元");
		} else {
			oldPrice.setText("商品原价：金币 " + new BigDecimal(StringUtil.checkNull(dealHistoryDetailObject.getGoodsOrgPriceCoin(), "0")).setScale(0, BigDecimal.ROUND_DOWN));
			paidPrice.setText("实际付款：金币 " + new BigDecimal(StringUtil.checkNull(dealHistoryDetailObject.getPayCoin(), "0")).setScale(0, BigDecimal.ROUND_DOWN));
		}
		expressInfoLayout.removeAllViews();
		expressInfoLayout.addView(CommUtil.createSingleLineTextView(mBaseActivity, "收件人名：" + StringUtil.checkNull(dealHistoryDetailObject.getReceiverName())));
		expressInfoLayout.addView(CommUtil.createSingleLineTextView(mBaseActivity, "联系电话：" + StringUtil.checkNull(dealHistoryDetailObject.getReceiverContact())));
		expressInfoLayout.addView(CommUtil.createSingleLineTextView(mBaseActivity, "收件地址：" + StringUtil.checkNull(dealHistoryDetailObject.getReceiverAddress())));
		productInfoLayout.removeAllViews();
		productInfoLayout.addView(CommUtil.createSingleLineTextView(mBaseActivity, "商户名称：" + StringUtil.checkNull(dealHistoryDetailObject.getGoodsBusinessName())));
		productInfoLayout.addView(CommUtil.createSingleLineTextView(mBaseActivity, "商品快照：" + StringUtil.checkNull(dealHistoryDetailObject.getGoodsOrgName())));
		orderDetailLayout.removeAllViews();
		orderDetailLayout.addView(CommUtil.createSingleLineTextView(mBaseActivity, "支付编号：" + StringUtil.checkNull(dealHistoryDetailObject.getPayId())));
		orderDetailLayout.addView(CommUtil.createSingleLineTextView(mBaseActivity, "创建时间：" + StringUtil.checkNull(dealHistoryDetailObject.getTime())));
		orderDetailLayout.addView(CommUtil.createSingleLineTextView(mBaseActivity, "支付时间：" + StringUtil.checkNull(dealHistoryDetailObject.getPayTime())));
		orderDetailLayout.addView(CommUtil.createSingleLineTextView(mBaseActivity, "关闭时间：" + StringUtil.checkNull(dealHistoryDetailObject.getCloseTime())));

		if(Integer.valueOf(dealHistoryDetailObject.getStatus()) == 1) {
			consumeGoldCoinLayout.setVisibility(View.GONE);
			payBtnLayout.setVisibility(View.VISIBLE);
		} else {
			consumeGoldCoinLayout.setVisibility(View.VISIBLE);
			payBtnLayout.setVisibility(View.GONE);
		}

		//取消订单
		if ("5".equalsIgnoreCase(dealHistoryDetailObject.getStatus())) {
			consumeGoldCoinLayout.setVisibility(View.GONE);
			payBtnLayout.setVisibility(View.GONE);
		}
	}

	private void cancelOrder() {
		HashMap<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("orderId", dealHistoryDetailObject.getPayId());
		ServiceHelper.send(mBaseActivity, ServiceHelper.CANCEL_ORDER, paramMap,
				new RequestCallBack<String>() {
					@Override
					public void onStart() {
						mBaseActivity.showDialog("提交中...");
					}

					@Override
					public void onCancelled() {
						mBaseActivity.closeDialog();
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						mBaseActivity.closeDialog();
						CommUtil.showAlert(mBaseActivity, "操作成功", "订单已经取消", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialogInterface, int i) {
								initOrderDetailData();
							}
						});
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						mBaseActivity.closeDialog();
						ToastUtils.toast(mBaseActivity, msg);
					}
				});
	}

	@OnClick(R.id.cancelOrderBtn)
	public void cancelOrderBtnClick(View view) {
		CommUtil.showConfirmAlert(mBaseActivity, "确认取消订单？", new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				cancelOrder();
			}
		}, null);
	}

	@OnClick(R.id.goHuiguoBtn)
	public void onGoHuiguoBtnClick(View view) {
		MainTabActivity.getInstance().setCurrentTab(1);
		WeDeOrdersFragment.setCloseInd(true);
		closeOtherActiviry();
	}

	@OnClick(R.id.goMianDanBtn)
	public void onMianDanBtnClick(View view) {
		MainTabActivity.getInstance().setCurrentTab(3);
		WeDeOrdersFragment.setCloseInd(true);
		closeOtherActiviry();
	}

	@OnClick(R.id.goYunGuoBtn)
	public void onYunGuoBtnClick(View view) {
		MainTabActivity.getInstance().setCurrentTab(2);
		WeDeOrdersFragment.setCloseInd(true);
		closeOtherActiviry();
	}

	private void closeOtherActiviry() {
		for (Activity activity : App.sActivityList) {
			if (activity.getIntent().getBooleanExtra(ExtraKeyConstant.KEY_FINISH_ACTIVITY, true)) {
				activity.finish();
			}
		}
	}

	@OnClick(R.id.continuePayBtn)
	public void continuePayBtnClick(View view) {
		if ("2".equalsIgnoreCase(dealHistoryDetailObject.getPayType())) {//现金支付要跳转到现金支付界面
			PayConfirmFragment.setRequestNo(1);
			xiaoFeiOrderConfirmObject.setId(dealHistoryDetailObject.getId());
			xiaoFeiOrderConfirmObject.setName(dealHistoryDetailObject.getName());
			xiaoFeiOrderConfirmObject.setPayMoney(dealHistoryDetailObject.getPayMoney());
			xiaoFeiOrderConfirmObject.setOrderNo(dealHistoryDetailObject.getPayId());
			xiaoFeiOrderConfirmObject.setCreateTime(dealHistoryDetailObject.getTime());
			xiaoFeiOrderConfirmObject.setPrice(dealHistoryDetailObject.getPayMoney());
			PayConfirmFragment.setXiaoFeiOrderConfirmObject(xiaoFeiOrderConfirmObject);
			CommUtil.openSingleFragmentActivity(mBaseActivity, PayConfirmFragment.class);
			mBaseActivity.finish();
		} else { //金币支付直接发起
			CommUtil.showTwoSelectAlert(mBaseActivity, "确认用我的金币支付？", "确定", "取消", new View.OnClickListener() {
				@Override
				public void onClick(View view) {
					submitGoldCoinPay();
				}
			}, null);
		}

	}

	private void submitGoldCoinPay() {
		HashMap<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("orderId", xiaoFeiOrderConfirmObject.getId());
		ServiceHelper.send(mBaseActivity, ServiceHelper.SUBMIT_GOLD_PAYMENT, paramMap,
				new RequestCallBack<String>() {
					@Override
					public void onStart() {
						mBaseActivity.showDialog("提交中...");
					}

					@Override
					public void onCancelled() {
						mBaseActivity.closeDialog();
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						mBaseActivity.closeDialog();
						CommUtil.showAlert(mBaseActivity, "兑换成功", "已支付成功", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialogInterface, int i) {
								initOrderDetailData();
							}
						});
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						mBaseActivity.closeDialog();
						ToastUtils.toast(mBaseActivity, msg);
					}
				});
	}


	public static void setXiaoFeiOrderConfirmObject(XiaoFeiOrderConfirmObject xiaoFeiOrderConfirmObject) {
		OrderDetailFrament.xiaoFeiOrderConfirmObject = xiaoFeiOrderConfirmObject;
	}

	public static void setDealHistoryDetailObject(DealHistoryDetailObject dealHistoryDetailObject) {
		OrderDetailFrament.dealHistoryDetailObject = dealHistoryDetailObject;
	}

	/**
	 * @return the homeFragmentInstent
	 */
	public static OrderDetailFrament getHomeFragmentInstent() {
		return homeFragmentInstent;
	}

}
